import tkinter as tk
from datetime import datetime
from lunardate import LunarDate


class ChineseClock:
    def __init__(self):
        # 时辰养生提示字典
        self.shichen_dict = {
            ("子时", "23:00-01:00"): "胆经运行，及时入睡养阳气",
            ("丑时", "01:00-03:00"): "肝经运行，深度睡眠助排毒",
            ("寅时", "03:00-05:00"): "肺经运行，保持温暖忌寒凉",
            ("卯时", "05:00-07:00"): "大肠经运行，起床饮水促排毒",
            ("辰时", "07:00-09:00"): "胃经运行，营养早餐要温食",
            ("巳时", "09:00-11:00"): "脾经运行，适当活动助运化",
            ("午时", "11:00-13:00"): "心经运行，小憩养神忌过劳",
            ("未时", "13:00-15:00"): "小肠经运行，补充水分助吸收",
            ("申时", "15:00-17:00"): "膀胱经运行，多喝温水促代谢",
            ("酉时", "17:00-19:00"): "肾经运行，少盐饮食护肾气",
            ("戌时", "19:00-21:00"): "心包经运行，放松心情宜休闲",
            ("亥时", "21:00-23:00"): "三焦经运行，准备入睡排烦恼"
        }

        # 农历月份转换
        self.lunar_months = ["正月", "二月", "三月", "四月", "五月", "六月",
                             "七月", "八月", "九月", "十月", "冬月", "腊月"]

        # 创建主窗口
        self.root = tk.Tk()
        self.root.title("中医养生时钟")
        self.root.attributes('-topmost', True)
        self.root.overrideredirect(True)
        self.root.config(bg='black')

        # 拖动相关变量
        self._drag_start_x = 0
        self._drag_start_y = 0

        # 创建界面组件
        self.create_widgets()

        # 绑定拖动事件
        self.bind_drag_events()

        # 初始位置
        self.set_initial_position()

        # 启动时间更新
        self.update_time()

    def bind_drag_events(self):
        """绑定窗口拖动事件到所有组件"""
        for child in self.root.winfo_children():
            child.bind("<ButtonPress-1>", self.start_drag)
            child.bind("<B1-Motion>", self.on_drag)
        self.root.bind("<ButtonPress-1>", self.start_drag)
        self.root.bind("<B1-Motion>", self.on_drag)

    def start_drag(self, event):
        """记录拖动起始位置"""
        self._drag_start_x = event.x
        self._drag_start_y = event.y

    def on_drag(self, event):
        """处理拖动事件"""
        x = self.root.winfo_x() - self._drag_start_x + event.x
        y = self.root.winfo_y() - self._drag_start_y + event.y
        self.root.geometry(f"+{x}+{y}")

    def set_initial_position(self):
        """设置初始位置在右上角"""
        screen_width = self.root.winfo_screenwidth()
        self.root.geometry(f"+{screen_width - 450}+20")

    def create_widgets(self):
        """创建界面组件"""
        time_font = ('微软雅黑', 24)
        info_font = ('微软雅黑', 14)

        # 公历时间标签
        self.gregorian_label = tk.Label(
            self.root,
            font=time_font,
            fg='#00FF00',
            bg='black'
        )
        self.gregorian_label.pack(pady=5)

        # 农历时间标签
        self.lunar_label = tk.Label(
            self.root,
            font=info_font,
            fg='#FFD700',
            bg='black'
        )
        self.lunar_label.pack()

        # 时辰提示标签
        self.shichen_label = tk.Label(
            self.root,
            font=info_font,
            fg='#FF6347',
            bg='black'
        )
        self.shichen_label.pack(pady=10)

    def get_shichen(self):
        """获取当前时辰及提示"""
        current_hour = datetime.now().hour
        for (name, time_range), tip in self.shichen_dict.items():
            start = int(time_range.split("-")[0].split(":")[0])
            end = int(time_range.split("-")[1].split(":")[0])
            # 处理跨天时辰（子时）
            if start > end:
                if current_hour >= start or current_hour < end:
                    return f"{name}（{time_range}）·{tip}"
            elif start <= current_hour < end:
                return f"{name}（{time_range}）·{tip}"
        return ""

    def get_lunar_date(self):
        """获取格式化农历日期"""
        now = datetime.now()
        lunar_date = LunarDate.fromSolarDate(now.year, now.month, now.day)

        # 转换月份
        month_str = self.lunar_months[lunar_date.month - 1]
        if lunar_date.isLeapMonth:
            month_str = "闰" + month_str

        # 转换日期
        day_str = self.number_to_chinese(lunar_date.day)

        return f"农历：{lunar_date.year}年{month_str}{day_str}"

    def number_to_chinese(self, num):
        """数字转中文日期（1-30）"""
        chinese_days = ["初一", "初二", "初三", "初四", "初五",
                        "初六", "初七", "初八", "初九", "初十",
                        "十一", "十二", "十三", "十四", "十五",
                        "十六", "十七", "十八", "十九", "二十",
                        "廿一", "廿二", "廿三", "廿四", "廿五",
                        "廿六", "廿七", "廿八", "廿九", "三十"]
        return chinese_days[num - 1]

    def update_time(self):
        """更新时间显示"""
        now = datetime.now()

        # 公历时间
        weekdays_zh = ["星期一", "星期二", "星期三",
                       "星期四", "星期五", "星期六", "星期日"]
        weekday_str = weekdays_zh[now.weekday()]
        gregorian_text = now.strftime(f"北京时间：%Y-%m-%d %H:%M:%S\n{weekday_str}")
        self.gregorian_label.config(text=gregorian_text)

        # 农历时间
        self.lunar_label.config(text=self.get_lunar_date())

        # 时辰提示
        self.shichen_label.config(text=self.get_shichen())

        # 每秒更新
        self.root.after(1000, self.update_time)


if __name__ == "__main__":
    clock = ChineseClock()
    clock.root.mainloop()